package com.gxuwz.com_property.utils;

import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.properties.PropertyValueEncryptionUtils;
import org.jasypt.util.text.BasicTextEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class JasyptEncryptorUtils {


   /* // 定义加密所需的 salt（盐）
    private static final String salt = "jiuzheyang";
    // 创建一个 BasicTextEncryptor 实例
    private static BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
    // 在静态块中，将 salt 设置为 BasicTextEncryptor 的密码
    static {
        basicTextEncryptor.setPassword(salt);
    }

    // 私有化构造方法，禁止外部实例化
    public JasyptEncryptorUtils(){}

    *//**
     * 明文加密
     * @param plaintext
     * @return
     *//*
    public static String encode(String plaintext){
        System.out.println("明文字符串：" + plaintext);
        // 使用 BasicTextEncryptor 对象对明文进行加密
        String ciphertext = basicTextEncryptor.encrypt(plaintext);
        System.out.println("加密后字符串：" + ciphertext);
        return ciphertext;
    }

    *//**
     * 解密
     * @param ciphertext
     * @return
     *//*
    public static String decode(String ciphertext){
        System.out.println("加密字符串：" + ciphertext);
        // 为密文添加 "ENC()" 前缀，以便 PropertyValueEncryptionUtils 判断其是否为加密值
        ciphertext = "ENC(" + ciphertext + ")";
        // 如果 ciphertext 是加密值，则对其进行解密
        if (PropertyValueEncryptionUtils.isEncryptedValue(ciphertext)){
            // 使用 PropertyValueEncryptionUtils.decrypt 方法和 BasicTextEncryptor 对象对密文进行解密

            String plaintext = PropertyValueEncryptionUtils.decrypt(ciphertext,basicTextEncryptor);
            System.out.println("解密后的字符串：" + plaintext);
            return plaintext;
        }
        System.out.println("解密失败");
        return "";
    }*/


    @Autowired
    private StringEncryptor encryptor;

    @Value("${jasypt.encryptor.password}")
    private String encryptorPassword;

    /**
     * 明文加密
     * @param plaintext 明文
     * @return 密文
     */
    public String encode(String plaintext) {
        return encryptor.encrypt(plaintext);
    }

    /**
     * 密文解密
     * @param ciphertext 密文
     * @return 明文
     */
    public String decode(String ciphertext) {
        return encryptor.decrypt(ciphertext);
    }

    /**
     * 获取加密器
     * @return StringEncryptor对象
     */
    public StringEncryptor getEncryptor() {
        StandardPBEStringEncryptor pbeStringEncryptor = new StandardPBEStringEncryptor();
        pbeStringEncryptor.setPassword(encryptorPassword);
        return pbeStringEncryptor;
    }

}


